package com.example.poc.user;

import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;

//import org.hibernate.envers.Audited;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Entity
//@Audited
@NoArgsConstructor
@Table(name = "users")
public class User implements UserDetails {

    @Id @GeneratedValue @Getter
    private Long id;

    @Getter @Setter
    private String email;

    @Getter @Setter
    @Column(unique = true)
    private String username;

    @Getter @Setter
    private String password;

    @Getter @Setter
    private boolean enabled;

    @Getter @Setter
    private boolean locked;

    @Getter @Setter
    @Column(name = "expiration_date")
    private Date expirationDate;

    @Setter @Getter
    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"))
    private Set<UserRole> roles = new HashSet<>();

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }

    @Override
    public boolean isAccountNonExpired() {
        return expirationDate == null || expirationDate.after(new Date());
    }

    @Override
    public boolean isAccountNonLocked() {
        return !isLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
}
